<template>
  <div class="visitor-notVisited f1 flex">
    <div class="left flex column">
      <div class="search-group">
        <div class="input-wrap" style="width: 2.5rem">
          <div class="label">MN码:</div>
          <div class="input-item">
            <a-input :maxLength="30" clearable v-model="queryParam.mn" placeholder="请输入MN码" />
          </div>
        </div>

        <div class="input-wrap" style="width: 2.5rem">
          <div class="label">设备状态:</div>
          <div class="input-item">
            <a-select ref="select" allowClear v-model="queryParam.status" placeholder="请选择设备状态">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="0">离线</a-select-option>
              <a-select-option value="1">在线</a-select-option>
            </a-select>
          </div>
        </div>

        <div class="input-wrap" style="width: 2.5rem">
          <div class="label">餐厅名称:</div>
          <div class="input-item">
            <a-input :maxLength="30" clearable v-model="queryParam.restaurantName" placeholder="请输入餐厅名称" />
          </div>
        </div>

        <div class="btn-wrap">
          <a-button class="searchBtn" @click="searchQuery()" type="primary">搜索</a-button>
          <a-button class="resetBtn" @click="searchReset()" type="primary">重置</a-button>
        </div>
      </div>

      <div class="table-wrap f1">
        <a-table
          rowKey="monitorMn"
          class="tableList"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :customRow="customRow"
          @change="handleTableChange"
          :scroll="{ x: 1000 }"
        >
          <template v-slot:status="records">
            <span v-if="records.status == 0">{{ '离线' }}</span>
            <span v-else style="color: #0eff47">{{ '在线' }}</span>
          </template>
        </a-table>
      </div>
    </div>

    <div class="right flex column">
      <div class="top f1 flex column">
        <div class="search-group">
          <div class="input-wrap" style="width: 2.6rem">
            <div class="label">选择时间:</div>
            <div class="input-item">
              <a-date-picker
                v-model="startValue"
                :allowClear="false"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择时间"
                @change="handleDatePickerChange"
                :disabled-date="disabledStartDate"
              />
            </div>
          </div>

          <div class="btn-wrap" style="margin-left: 15px">
            <span style="position: relative">
              <a-button class="searchBtn" type="primary" @click="isShowPopover = true">筛选</a-button>
              <div class="popover" v-if="isShowPopover">
                <div class="search-group">
                  <div class="input-wrap">
                    <div class="label">选择参数:</div>
                    <div class="input-item">
                      <a-select ref="select" allowClear v-model="column" placeholder="请选择参数">
                        <a-select-option value="thickSmokeAvg">油烟数值</a-select-option>
                        <a-select-option value="particleHazeAvg">颗粒度浓度</a-select-option>
                        <a-select-option value="nonMethaneAvg">非甲烷气体</a-select-option>
                      </a-select>
                    </div>
                  </div>

                  <div class="input-wrap">
                    <div class="label">大于:</div>
                    <div class="input-item">
                      <a-input-number clearable v-model="minValue" placeholder="请输入阈值" />
                    </div>
                  </div>

                  <div class="input-wrap">
                    <div class="label">小于:</div>
                    <div class="input-item">
                      <a-input-number clearable v-model="maxValue" placeholder="请输入阈值" />
                    </div>
                  </div>

                  <div class="btn-group flex justify-around" style="margin-top: 0.1rem; padding: 0 0.2rem">
                    <a-button
                      type="primary"
                      class="searchBtn"
                      @click="isShowPopover = false"
                      style="background: #deef35 !important"
                    >
                      取消
                    </a-button>
                    <a-button class="searchBtn" @click="confimFilter()" type="primary">确定</a-button>
                  </div>
                </div>
              </div>
            </span>
            <a-button class="searchBtn" @click="getEchartsData(monitorMn)" type="primary">搜索</a-button>
            <a-button class="resetBtn" @click="resetFilter" type="primary">重置</a-button>

            <a-button @click="exportExcel('设备排名小时数据')" type="primary" class="exp">批量导出</a-button>
          </div>
        </div>

        <e-charts :options="historyTimeData" class="f1"></e-charts>
      </div>

      <div class="bot f1">
        <a-table
          rowKey="id"
          class="tableList"
          :columns="columns2"
          :dataSource="dataSource2"
          :pagination="ipagination2"
          @change="handleTableChange2"
        ></a-table>
      </div>
    </div>
  </div>
</template>
<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import eCharts from '@/components/eCharts'
import JInput from '@/components/jeecg/JInput'
import { getAction, downFile } from '@/api/manage'
import { historyTimeData } from './modules/echartsData'
import { mapState } from 'vuex'
export default {
  name: 'visitor-notVisited',
  mixins: [JeecgListMixin],
  computed: {
    ...mapState({
      isAgencyId: (state) => state.user.isAgencyId,
    }),
  },
  watch: {
    isAgencyId(v) {
      this.queryParam.unitId = v.id ? v.id : ''
      this.searchQuery()
    },
  },
  components: { eCharts, JInput },
  data() {
    return {
      url: {
        list: '/device/statistics_page',
        exportXlsUrl: '/device/regular_data/export?type=2',
        tree: true,
      },
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '行政区域',
          dataIndex: 'regionName',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '设备MN码',
          dataIndex: 'monitorMn',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '状态',
          scopedSlots: { customRender: 'status' },
          align: 'center',
        },
        {
          title: '安装餐厅',
          dataIndex: 'restaurantName',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '联系人',
          dataIndex: 'chargeName',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '联系电话',
          dataIndex: 'chargePhone',
          align: 'center',
          ellipsis: true,
        },
      ],
      ipagination: {
        current: 1,
        pageSize: 8,
        pageSizeOptions: ['5', '10', '20'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        // onShowSizeChange: (current, pageSize) => this.onSizeChange(current, pageSize),
        showQuickJumper: false,
        showSizeChanger: false,
        total: 0,
      },

      startValue: '',
      monitorMn: '',
      historyTimeData: {},

      startDate: '',
      endDate: '',
      column: 'thickSmokeAvg',
      maxValue: '',
      minValue: '',
      isShowPopover: false,

      columns2: [
        {
          title: '日期',
          dataIndex: 'date',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '时间',
          dataIndex: 'time',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '油烟(mg/m³)',
          dataIndex: 'thickSmokeAvg',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '颗粒物(mg/m³)',
          dataIndex: 'particleHazeAvg',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '非甲烷总烃(mg/m³)',
          dataIndex: 'nonMethaneAvg',
          ellipsis: true,
          align: 'center',
        },
      ],
      ipagination2: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        // onShowSizeChange: (current, pageSize) => this.onSizeChange(current, pageSize),
        showQuickJumper: false,
        showSizeChanger: false,
        total: 0,
      },
      dataSource2: [],
    }
  },
  mounted() {
    this.startValue = this.$moment().startOf('day').format('YYYY-MM-DD')
    this.startDate = this.$moment().startOf('day').valueOf()
    this.endDate = this.$moment().endOf('day').valueOf()

    setTimeout(() => {
      this.getEchartsData(this.dataSource[0].monitorMn)
    }, 1000)
  },
  methods: {
    customRow(record, index) {
      let _this = this
      return {
        on: {
          click: (event) => {
            // 鼠标单击行
            _this.records = record
            _this.getEchartsData(_this.records.monitorMn)

            const oldList = document.querySelectorAll('.checked-td-of-add-table')
            if (oldList) {
              for (let j = 0; j < oldList.length; j++) {
                oldList[j].classList.remove('checked-td-of-add-table')
              }
            }

            const children = event.target.parentNode.children
            for (let i = 0; i < children.length; i++) {
              children[i].classList.add('checked-td-of-add-table')
            }
          },
        },
      }
    },

    disabledStartDate(startValue) {
      const endValue = this.endValue
      if (endValue) {
        return startValue.valueOf() >= endValue.valueOf()
      }
      return startValue.valueOf() > new Date().getTime()
    },

    handleDatePickerChange() {
      this.startDate = this.$moment(`${this.startValue + ' 00:00:00'}`).valueOf()
      this.endDate = this.$moment(`${this.startValue + ' 23:59:59'}`).valueOf()
    },

    async getEchartsData(monitorMn) {
      this.monitorMn = monitorMn

      let params = {
        type: 2,
        monitorMn: this.monitorMn,
        endDate: this.endDate,
        startDate: this.startDate,
      }
      let { result } = await getAction('/device/regular_data/map', params)
      this.historyTimeData = historyTimeData(result)

      this.getTableSource()
    },

    async getTableSource() {
      let params = {
        type: 2,
        endDate: this.endDate,
        startDate: this.startDate,
        monitorMn: this.monitorMn,
        column: this.column,
        maxValue: this.maxValue,
        minValue: this.minValue,
        pageNo: this.ipagination2.current,
        pageSize: this.ipagination2.pageSize,
      }

      let { result } = await getAction('/device/regular_data/page', params)
      this.dataSource2 = result.records
      this.ipagination2.total = result.total
    },

    async confimFilter() {
      if (this.maxValue !== '' || this.minValue !== '') {
        this.getTableSource()
        this.isShowPopover = false
      } else {
        this.isShowPopover = false
      }
    },

    async resetFilter() {
      this.isShowPopover = false
      this.column = 'thickSmokeAvg'
      this.maxValue = ''
      this.minValue = ''
      this.startValue = this.$moment().startOf('day').format('YYYY-MM-DD')
      this.startDate = this.$moment().startOf('day').valueOf()
      this.endDate = this.$moment().endOf('day').valueOf()

      let params = {
        type: 2,
        endDate: this.endDate,
        startDate: this.startDate,
        monitorMn: this.monitorMn,
        pageNo: 1,
        pageSize: this.ipagination2.pageSize,
      }

      let { result } = await getAction('/device/regular_data/page', params)
      this.dataSource2 = result.records
      this.ipagination2.total = result.total

      let { result: map } = await getAction('/device/regular_data/map', params)
      this.historyTimeData = historyTimeData(map)
    },

    handleTableChange2(pagination) {
      this.ipagination2 = pagination
      this.getTableSource()
    },

    exportExcel(fileName) {
      let params = {
        type: 2,
        unitId: sessionStorage.getItem('agencyId'),
        monitorMn: this.monitorMn,
        column: this.column,
        minValue: this.minValue,
        maxValue: this.maxValue,
        endDate: this.endDate,
        startDate: this.startDate,
      }
      this.handleExportXls(fileName, params)
    },

    handleExportXls(fileName, tempParams) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = this.getQueryParams()
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      param = { ...tempParams }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(
            new Blob([data], {
              type: 'application/vnd.ms-excel',
            }),
            fileName + '.xls',
          )
        } else {
          let url = window.URL.createObjectURL(
            new Blob([data], {
              type: 'application/vnd.ms-excel',
            }),
          )
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .checked-td-of-add-table {
  background-color: rgba(12, 183, 188, 0.5);
}
/deep/ .ant-table-tbody > tr > td {
  cursor: pointer;
}

.visitor-notVisited {
  background: #024c4e;
  padding-top: 6px;
  min-height: 0;
  min-width: 0;
}

.left {
  flex: 6;
  border-right: 1px solid#036265;
  min-height: 0;
  min-width: 0;
}
.table-wrap {
  overflow: scroll;
}
.right {
  flex: 10;
}

.exp {
  margin-left: 0.1rem;
  background: #045053;
  border: 1px solid #017f82;
  font-size: 0.14rem;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  color: #00f8ff;
}

.popover {
  position: absolute;
  top: 100%;
  left: -180%;
  z-index: 1;
  transform: translateY(5%);
  width: 3.2rem;
  background: #076063;
  border: 1px solid #047578;
}
</style>
